import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/service/resource_service.dart';
import 'package:sports_new/entity/other/resource_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/online_contact.dart';
import 'package:sports_new/utils/sp_utils.dart';
import 'package:sports_new/utils/toast_utils.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/my/widgets/my_appbar.dart';
import 'package:sports_new/widgets/base/qkd_dialog.dart';
import '../../widgets/base/qkd_text.dart';
// import 'package:flutter_qiyu/flutter_qiyu.dart';

class MyContactPage extends StatefulWidget {
  const MyContactPage({super.key});

  @override
  State<MyContactPage> createState() => _MyContactPageState();
}

class _MyContactPageState extends State<MyContactPage> {
  String qq = "1246786881";
  String wx = "QXB_kefu";

  final imageNames = const {
    "qq": "my_con_qq.png",
    "wx": "my_con_wx.png",
    "mail": "my_con_mail.png",
    "online": "my_contact_online.png"
  };

  List<ResourceEntity> btnRes = [
    ResourceEntity(title: "qq", content: "1246786881", button: "QQ客服"),
    ResourceEntity(title: "wx", content: "QXB_kefu", button: "微信客服"),
    ResourceEntity(title: "mail", content: "", button: "邮箱客服")
  ];

  List<ResourceEntity> tips = [
    ResourceEntity(
        title: "tip",
        content: "1.您可复制上方微信号或QQ号添加球客岛官方客服，与我们联系，也可通过微信在线客服与我们即时沟通。"),
    ResourceEntity(
        title: "tip", content: "2.客服工作时间：工作日8:30至22:00，休息日10:00至18:00。")
  ];

  _solvAppContactRes(List<ResourceEntity> res) {
    if (res.isEmpty) {
      return;
    }
    btnRes.clear();
    tips.clear();
    for (var element in res) {
      if (element.button == 'expert_cs') {
        continue;
      }
      if (element.title == "tip") {
        tips.add(element);
      } else {
        btnRes.add(element);
      }
    }
    update();
  }

  _getContactInfo() async {
    final list = Get.find<ResourceService>().contact ?? [];
    _solvAppContactRes(list);
    _saveContactToSp();
    update();
  }

  _getContactFromSp() {
    try {
      final res = (SpUtils.appContact?["list"] as List)
          .map((e) => ResourceEntity.fromJson(e))
          .toList();
      _solvAppContactRes(res);
    } catch (err) {}
  }

  _saveContactToSp() {
    SpUtils.appContact = {
      "list": (btnRes + tips).map((e) => e.toJson()).toList()
    };
  }

  unreadChange(int count) {
    update();
  }

  @override
  void initState() {
    super.initState();
    _getContactFromSp();
    _getContactInfo();
    // OnlineContact.instance.inChatWindow = true;
    // QiYu.registerListener(unreadChange);
  }

  @override
  void dispose() {
    // QiYu.unregisterListener(unreadChange);
    // OnlineContact.instance.inChatWindow = false;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF7F7F7),
      appBar: const MyAppBar(title: "客服中心"),
      body: Column(
        children: [
          const SizedBox(height: 10),
          Styles.card(
            margin: const EdgeInsets.symmetric(horizontal: 8),
            child: Column(
              children: [
                ...btnRes.map((e) {
                  final islast = btnRes.last == e;
                  return Column(
                    children: [
                      _cell(e,isCopy: !(e.button == "qiyu" || e.button == "在线客服")),
                      if (!islast)
                        const Divider(
                            height: 0.5, color: Color(0xffeeeeee), indent: 16)
                    ],
                  );
                })
              ],
            ),
          ),
          const SizedBox(height: 10),
          ...tips.map(
            (e) => Container(
              alignment: Alignment.topLeft,
              margin: const EdgeInsets.only(left: 20, right: 20, bottom: 4),
              child: QkdText(
                e.content ?? "",
                fontSize: 13,color: Colours.grey99,
              ),
            ),
          ),
        ],
      ),
    );
  }

  _cell(ResourceEntity entity, {bool isCopy = true}) {
    final title = entity.title ?? "";
    final sub = entity.content ?? "";
    Map<String,dynamic>? map;
    if(entity.extInfo?.contains("{") == true){
      map = jsonDecode(entity.extInfo ?? "");
    }
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () async{
        if(isCopy) {
          Clipboard.setData(ClipboardData(text: sub));
          ToastUtils.show("已复制 $sub");
        }else{
          if(entity.button == "qiyu"){
            OnlineContact().openServiceWindow();
          }else {
            var result = await Get.dialog(
              const QkdDialog.alertBUTTON("",
                content: "您好，您可以在每日的09：00-18:00通过微信客服联系我们。其它时间可以进行留言，客服会在工作时间尽快回复，感谢您的理解和支持。",
                confirmText: "联系客服",
              )
            );
            if(result == true && map != null) {
              Fluwx().open(
                  target: CustomerServiceChat(
                      corpId: map["cropId"],
                      url: map["url"]
                  )
              );
            }
          }
        }
      },
      child: Container(
        height: 52,
        padding: const EdgeInsets.only(left: 12, right: 12),
        color: Colors.white,
        child: Row(
          children: [
            SizedBox(
              width: 24,
              height: 24,
              child: CachedNetworkImage(
                imageUrl: entity.imgUrl ?? "",
                placeholder: (context, url) => Styles.placeholderIcon(),
                errorWidget: (context, url, error) => Styles.placeholderIcon(),
              ),
            ).marginOnly(right: 10),
            QkdText(title,fontSize: 16),
            const Spacer(),
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                QkdText(sub, needCenter: true,color: Colours.grey66),
                const SizedBox(width: 10),
                Image.asset(
                  Utils.getImgPath(isCopy?"my_copy.png":"arrow_right_36.png"),
                  width: 14, height: 14
                )
              ],
            ),
          ],
        ),
      ),
    );
  }
}
